#include <iostream>
using namespace std;

int n;
int m;
char grid[405][405];
bool v[405][405];
int x;
int y;
int dr[4] = {-1, 0, 1, 0};
int dc[4] = {0, -1, 0, 1};
int ans;

bool ok(int r, int c) {
    if (r < 0 || c < 0 || r >= n || c >= n) return 0;
    return 1;
}

void dfs(int r, int c, int cnt) {
    for(int i=0;i<4;i++){
        int fr = r + dr[i];
        int fc = c + dc[i];
        if(!ok(fr, fc)) continue;
        if(v[fr][fc]) continue;
        if(grid[fr][fc] == grid[r][c]) continue;
        v[fr][fc] = 1;
        dfs(fr,fc,cnt+1);
        v[fr][fc] = 0;
    }
    ans = max(ans, cnt+1);
    return;
}

int main() {
    cin >> n;
    cin >> m;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) cin >> grid[i][j];
    while (m--) {
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++) v[i][j] = 0;
        cin >> x;
        cin >> y;
        x--;
        y--;
        ans = -1;
        v[x][y] = 1;
        dfs(x,y,0);
        cout << ans << endl;
    }
    return 0;
}